<template>
  <!-- 会员类型管理 -->
  <!-- 王旭 2023年8月14日 20点20分 -->
  <div>
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="89px"
    >
      <el-form-item label="类型名称" prop="memberName">
        <el-input
          v-model="queryParams.memberName"
          placeholder="请输入会员类型名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
      </el-form-item>
    </el-form>
    <!-- 新增按钮模块 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-search"
          size="mini"
          @click="handleSearchList"
          >本月会员购买记录查询</el-button
        >
      </el-col>
    </el-row>
    <!-- 列表数据展示 -->
    <el-table
      v-loading="loading"
      :data="menberList"
      :header-cell-class-name="'headerBg'"
      class="bold-header"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="编号" align="center" prop="id" />
      <el-table-column label="会员类型名称" align="center" prop="memberName" />
      <el-table-column label="会员有效期(月)" align="center" prop="duration" />
      <el-table-column label="开通价格(元)" align="center" prop="price" />
      <el-table-column label="适用范围" align="center" prop="memberScope" />       
            <el-table-column
            align="center"
            prop="liveRoomStatus"
            label="启用/禁用">
            <!-- 滑块开关 -->
            <template slot-scope="scope">
          <el-tag type="danger" v-if="scope.row.isDisable === 1"> 禁用 </el-tag>
          <el-tag type="success" v-else> 正常 </el-tag>
        </template>
            <template slot-scope="scope">
                <el-switch v-model="scope.row.isDisable"
                    active-color="#13ce66"
                    inactive-color="#ff4949"
                    :active-value="0"
                    :inactive-value="1"
                    @change=toggleDisableStatus(scope.row)>
                </el-switch>
            </template>
            </el-table-column>
      <el-table-column label="图片" align="center">
        <template slot-scope="scope">
          <!-- 图片回显 -->
          <el-image
            style="width: 100px; height: 100px"
            :src="
              'http://101.43.223.224:8765/image/getImageById?id=' +
              scope.row.memberUrl
            "
          >
          </el-image>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
        fixed="right"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加或修改窗口 -->
    <el-dialog :title="title" :visible.sync="open" width="20%" append-to-body>
      <el-form
        ref="addForm"
        :model="addForm"
        label-width="100px"
        :rules="rules"
        class="form-container"
        :inline="true"
      >
        <el-input
          v-model="addForm.id"
          placeholder="id"
          type="hidden"
        ></el-input>
        <el-form-item label="图片">
          <el-upload
            action=""
            list-type="picture-card"
            class="avatar-uploade"
            :show-file-list="false"
            :before-upload="beforeAvatarUpload"
          >
              <img
                height="210"
                v-if="memberUrl"
                :src="memberUrl"
                class="avatar"
              />
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="类型名称" prop="memberName">
          <el-input
            v-model="addForm.memberName"
            placeholder="请输入类型名称"
          ></el-input>
        </el-form-item>
        <el-form-item label="有效期(月)" prop="duration">
          <el-input
            v-model="addForm.duration"
            type="number"
            placeholder="请输入会员有效期"
            :readonly="!isEdit"
          ></el-input>
        </el-form-item>
        <el-form-item label="价格(元)" prop="price">
          <el-input
            v-model="addForm.price"
            placeholder="请输入开通价格"
          ></el-input>
        </el-form-item>
        <el-form-item label="折扣(%)" prop="discount">
          <el-input
            v-model="addForm.discount"
            placeholder="请输入可使用折扣"
          ></el-input>
        </el-form-item>
        <el-form-item label="适用范围" prop="memberScope">
          <el-input
            v-model="addForm.memberScope"
            placeholder="请输入适用范围"
          ></el-input>
        </el-form-item>
        <el-form-item label="特权介绍" prop="privilege">
          <el-input
            v-model="addForm.privilege"
            placeholder="请输入特权介绍"
          ></el-input>
        </el-form-item>
        <div class="button-container">
          <el-button type="primary" @click="submitForm('form')">提交</el-button>
          <el-button @click="cancelAll">取消</el-button>
        </div>
      </el-form>
    </el-dialog>

    <!--分页效果-->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="currentPage4"
      :page-sizes="[10, 15, 20, 25]"
      :page-size="queryParams.pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
    >
    </el-pagination>
  </div>
</template>
<script>
import { Message } from "element-ui";
export default {
  data() {
    return {
      isEdit: false,
      // 添加时赋值
      imgEducation: "",
      // 图片回显
      memberUrl: "",
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 表格数据
      menberList: [],
      // 显示搜索条件
      showSearch: true,
      // 查询参数
      queryParams: {
        memberName: null,
        // 第几页
        pageNum: 1,
        // 每页条数
        pageSize: 10,
        // 总条数
        total: 0,
      },
      // 总条数
      total: 0,
      // 当前页码
      currentPage4: 1,
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 表单参数
      addForm: {},
      // 表单校验
      rules: {
        memberName: [
          { required: true, message: "请输入类型名称", trigger: "blur" },
        ],
        duration: [
          { required: true, message: "期限不能为空" },
        ],
        price: [{ required: true, message: "价格不能为空" }],
        discount: [{ required: true, message: "折扣不能为空" }],
        memberScope: [
          { required: true, message: "请输入适用范围", trigger: "blur" },
        ],
      },
    };
  },
  created() {
    this.getList();
  },
  methods: {
    // 跳转至会员购买记录页面
    handleSearchList () {
      this.$router.push('/memberManagerInfo')
    },
    // 模糊查询操作
    handleQuery() {
      const that = this;
      this.loading = true;
      this.$axios
        .post("/memberType/selectMemberType", {
          pageNum: that.queryParams.pageNum,
          pageSize: that.queryParams.pageSize,
          memberName: that.queryParams.memberName,
        })
        .then((res) => {
          this.menberList = res.data.data.content;
          this.total = res.data.data.totalSize;
          this.loading = false;
        });
    },
    // 全查操作
    getList() {
      const that = this;
      this.loading = true;
      this.$axios
        .post("/memberType/selectMemberType", {
          pageNum: that.queryParams.pageNum,
          pageSize: that.queryParams.pageSize,
        })
        .then((res) => {
          this.menberList = res.data.data.content;
          this.total = res.data.data.totalSize;
          this.loading = false;
        });
    },
    // 查询一条操作
    handleFind(row) {
      this.title = "查看会员类型信息";
      this.open = true;
      this.loading = true;
      this.shaoSaveButton = false;
      this.$axios
        .get("/memberType/fingById?id=" + row.id)
        .then((res) => {
          this.addForm = res.data.data;
          this.loading = false;
          this.memberUrl =
            "http://101.43.223.224:8765/image/getImageById?id=" +
            res.data.data.memberUrl;
        });
    },
    // 修改按钮操作
    handleUpdate(row) {
      if (row.isDisable === 1) {
        // 添加判断条件
        this.open = true;
        this.handleFind(row);
        this.title = "修改会员信息";
        this.isEdit = false; // 设置为只读状态
      } else {
        // isDisable 不等于 1，不能打开修改窗口
        Message.error("该会员信息正在启用，无法修改！！！");
      }
    },
    // 删除
    handleDelete(row) {
      const that = this;
      if(row.isDisable === 0){
        Message.error("该会员信息正在启用，无法修改！！！");
      }else{
      this.$confirm("此操作将永久删除该类型, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.$axios
            .get("/memberType/deleteById?id=" + row.id)
            .then((res) => {
              this.$message({ type: "success", message: "删除成功" });
              that.getList();
            });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
      }
    },
    // 文件上传校验
    beforeAvatarUpload(file) {
      //上传图片格式
      const isJPG = file.type === "image/jpeg";
      const isPNG = file.type === "image/png";
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isJPG && !isPNG) {
        this.$message.error("上传图片只能是JPG/PNG格式!");
        return false;
      }
      if (!isLt2M) {
        this.$message.error("上传图片大小不能超过2MB!");
        return false;
      }
      //赋值
      this.imgEducation = file;
      this.memberUrl = URL.createObjectURL(file);
      //isJPG && isLt2M 自动提交 false 是点击确定后提交
      return false;
    },
    // 提交按钮
    submitForm() {
      this.$refs["addForm"].validate((valid) => {
        if (valid) {
          let isImageChanged = false;
          // 定义一个form对象
          const formData = new FormData();
          // 存入输入的值
          formData.append("memberName", this.addForm.memberName);
          formData.append("duration", this.addForm.duration);
          formData.append("price", this.addForm.price);
          formData.append("discount", this.addForm.discount);
          formData.append("memberScope", this.addForm.memberScope);
          formData.append("privilege", this.addForm.privilege);
          // 图片
          if (this.imgEducation && this.imgEducation !== this.memberUrl) {
            formData.append("file", this.imgEducation, this.imgEducation.name);
            isImageChanged = true;
         }
          if (this.addForm.id != null) {
            // 将id赋值
            formData.append("id", this.addForm.id);
            // 判断是否修改了图片，若未修改则使用当前的memberUrl
           if (!isImageChanged) {
             formData.append("memberUrl", this.addForm.memberUrl);
           }
            // 修改方法
            this.$axios
              .post(
                "/memberType/updateMemberType",
                formData
              )
              .then((res) => {
                if (res.data.code === 200) {
                  this.$message({ type: "success", message: "修改成功" });
                  // 关闭窗口
                  this.open = false;
                  //刷新
                  this.getList();
                } else {
                  this.$message.error({ type: "warning", message: "修改失败" });
                }
              });
          } else {
            this.$axios
              .post("/memberType/addMemberType", formData)
              .then((res) => {
                if (res.data.code === 200) {
                  this.$message({ type: "success", message: "添加成功" });
                  // 关闭窗口
                  this.open = false;
                  //刷新
                  this.getList();
                } else {
                  this.$message.error({ type: "warning", message: "添加失败" });
                }
              });
          }
        }
      });
    },
    // 取消按钮
    cancelAll() {
      this.open = false;
    },
    // 新增按钮操作
    handleAdd() {
      this.open = true;
      this.title = "添加会员类型";
      // 清除表单数据
      if (this.$refs.addForm !== undefined) {
        this.$refs.addForm.resetFields();
        this.memberUrl='';
      }
      this.addForm.id = null
      this.isEdit = true; // 设置为可编辑状态
    },
    // 启用禁用状态按钮
    toggleDisableStatus(row) {
      const id = row.id;
      const isDisable = row.isDisable;
      if(row.isDisable === 1){
        this.$axios
        .post("/memberType/updateModify", {
          id,
          isDisable,
        })
        .then((res) => {
          this.$message({ type: "error", message: "禁用成功" });
          this.getList();
          // 处理成功
        });
      }else{
        this.$axios
        .post("/memberType/updateModify", {
          id,
          isDisable,
        })
        .then((res) => {
          this.$message({ type: "success", message: "启用成功" });
          this.getList();
          // 处理成功
        });
      }
      
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.lid);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    // 分页每页条数显示
    handleSizeChange(val) {
      this.queryParams.pageSize = val;
      this.getList();
      console.log(`每页 ${val} 条`);
    },
    // 分页当前页显示
    handleCurrentChange(val) {
      this.currentPage4 = val;
      this.queryParams.pageNum = val;
      this.getList();
      console.log(`当前页: ${val}`);
    },
  },
};
</script>
<style>
.headerBg {
  background: #eee !important;
}
.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 150px;
    height: 150px;
    line-height: 150px;
    text-align: center;
  }
  .avatar {
    width: 150px;
    height: 150px;
    display: block;
  }

.bold-header .el-table__header th {
  font-weight: bold;
}
.button-container {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}
</style>